"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-05-20 10:35:00
LastEditTime: 2025-05-19 01:04:27
FilePath: LibraryManagerStudio/web/routes/utils.py
"""
import base64
import json

from Crypto.Cipher import AES
from fastapi import Depends, UploadFile
from loguru import logger

from ..deps import get_db
from ...database import DBManager
from ...datamodel import User


async def save_cover(cover: UploadFile) -> str:
    """
    save the book or user cover

    !Attention : this version only can save image by base 64

    Args:
        cover: UploadFile

    Returns:
        str: base64 code
    """
    image_content = await cover.read()
    return base64.b64decode(image_content).decode("utf-8")

def verify_admin(uid: str, db: DBManager) -> bool:
    """验证管理员身份"""
    user = db.get(User, filters={"uid": uid})
    logger.warning(f"verify_admin")
    if user.data[0]['is_admin']:
        return True
    return False


class WXBizDataCrypt:
    def __init__(self, appId, sessionKey):
        self.appId = appId
        self.sessionKey = sessionKey

    def decrypt(self, encryptedData, iv):
        # base64 decode
        sessionKey = base64.b64decode(self.sessionKey)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))

        if decrypted['watermark']['appid'] != self.appId:
            raise Exception('Invalid Buffer')

        return decrypted

    def _unpad(self, s):
        return s[:-ord(s[len(s) - 1:])]
